import axios from '../src/axios.js';

axios.defaults.baseURL = './index.html';
const {cancel, token} = axios.getCancelAndToken();

axios.interceptor.request.use(config => {
  config.url = './index.json';
  // 在这里配置url，测试请求拦截是否成功
  console.log(`请求拦截成功,修改请求url为：${config.url}`);
  return config;
});

axios.interceptor.request.use(config => {
  config.headers['Content-Type'] = 'application/json';
  console.log(`请求拦截成功,修改请求头为：${config.headers['Content-Type']}`);
  return config;
});

// axios.interceptor.request.use(config => {
//   console.log('自定义状态码校验函数');
//   config.validateStatus = function (status) {
//     console.log('自定义状态码校验函数，当前的状态码为：' + status);
//     return status !== 200;
//   };
//   return config;
// });

axios.interceptor.response.use(
  response => {
    response.response1 = 'response1';
    console.log('响应拦截成功，在response中添加属性response1');
    return response;
    // return Promise.reject('err');
  },
  reason => Promise.reject(reason)
);
axios.interceptor.response.use(
  response => {
    response.response2 = 'response2';
    console.log('响应拦截成功，在response中添加属性request2');
    return response;
  },
  reason => Promise.reject(reason)
);

export default function testAxios() {
  return axios({
    method: 'get',
    // url: 'https://somewhere.org/i-dont-exist',
    url: '',
    headers: {
      'Content-Type': 'text/html'
    },
    cancelToken: token,
    timeout: 1000,
    validateStatus: function (status) {
      console.log('自定义状态码校验函数，当前的状态码为：' + status);
      return status !== 200;
    }
  })
    .then(response => {
      console.log(response);
      console.log(JSON.parse(response.data));
    })
    .catch(reason => {
      console.log(reason);
    });
}
